// src/service/tencent.service.ts
import { Config, Init, Inject, Provide } from '@midwayjs/core';
import * as COS from 'cos-nodejs-sdk-v5';
import { UploadFileInfo } from '@midwayjs/busboy';
import Utils from '../utils';

@Provide()
export class TencentService {
  @Config('cos')
  cosConfig: {
    appId: string;
    secretId: string;
    secretKey: string;
    bucket: string;
    region: string;
  };

  @Inject()
  private utils: Utils;

  private cosBaseDir = '/stick';

  private cos: COS;

  @Init()
  async init(): Promise<void> {
    this.cos = new COS({
      SecretId: this.cosConfig.secretId,
      SecretKey: this.cosConfig.secretKey
    });
  }

  /**
   * 高级上传（支持断点续传、并发分块）
   * @param file Midway 上传文件对象
   * @param saveDir  COS 目标目录
   * @returns 上传后的访问 URL 及 COS 对象键
   */
  uploadFile(file: UploadFileInfo) {
    return new Promise<
      ReturnType<
        | typeof this.utils.response.success<string>
        | typeof this.utils.response.fail
      >
    >(resolve => {
      // 根据年月 如：/2025/08 组成savedir
      const dir = this.utils.dateFormat(new Date(), 'YYYY/MM');
      const key = `${
        this.cosBaseDir
      }/${dir}/${this.utils.createSnowflakeId16()}_${file.filename}`;

      this.cos.uploadFile(
        {
          Bucket: this.cosConfig.bucket,
          Region: this.cosConfig.region,
          Key: key,
          FilePath: file.data, // 本地临时文件绝对路径
          SliceSize: 1024 * 1024 * 5 // ≥5 MB 自动分块
        },
        (err, data) => {
          if (err) {
            resolve(this.utils.response.fail(err.message, 500));
          } else {
            resolve(
              this.utils.response.success<string>(
                `https://${data.Location}`,
                '文件上传成功'
              )
            );
          }
        }
      );
    });
  }
}
